// pages/home/home.js
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
import Toast from '@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    TabList: [],
    list: [],
    id: 0,
    show: false, // 显示更多弹窗
    channelAllList: [],
    recommendList: [],
    delVisible: false, // 是否点击编辑
    title: '推荐',
    loadingList: []
  },

  // 跳转到搜索页面
  toSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },

  // 删除频道、跳转
  async delChannel(e) {
    console.log(e);
    console.log(e.currentTarget.dataset);
    // 处于编辑状态下，才能删除，不处于编辑状态为跳转
    if (!this.data.delVisible) {
      // 跳转
      this.setData({
        show: false,
        id: e.currentTarget.dataset.id,
        title: e.currentTarget.dataset.name
      })
      // 获取列表
      this.getList()
    } else {
      if (e.currentTarget.dataset.id === 0) return
      // toast 提示
      Toast.loading({
        message: '删除中...',
        forbidClick: true,
      });
      const res = await wx.p.request({
        url: `https://toutiao.itheima.net/v1_0/user/channels/${e.currentTarget.dataset.id}`,
        method: 'DELETE',
        header: {
          Authorization: `Bearer ${store.token}`
        },
      })
      console.log(res);
      var newRecommendList = this.data.recommendList
      newRecommendList.push({ id: e.currentTarget.dataset.id, name: e.currentTarget.dataset.name })
      this.setData({ 
        recommendList: newRecommendList,
        TabList: this.data.TabList.filter(item => item.id !==e.currentTarget.dataset.id)
      })
      Toast.success('删除成功')
    }
  },

  // 编辑
  edit() {
    if(this.data.delVisible) {
      // 如果已经处于编辑状态，隐藏后直接返回
      this.setData({ delVisible: false })
      return
    }
    this.setData({ delVisible: true })
  },

  // 添加频道
  async addChannel(e) {
    // toast 提示
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    });
    console.log(e.currentTarget.dataset.id);
    const res = await wx.p.request({
      url: 'https://toutiao.itheima.net/v1_0/user/channels',
      header: {
        Authorization: `Bearer ${store.token}`
      },
      method: 'PATCH',
      data: {
        channels: [{ id: e.currentTarget.dataset.id, seq: this.data.TabList.length + 1 }]
      }
    })
    console.log(res);
    var newTabList = this.data.TabList
    newTabList.push({ id: e.currentTarget.dataset.id, name: e.currentTarget.dataset.name })
    this.setData({ 
      TabList: newTabList,
      recommendList: this.data.recommendList.filter(item => item.id !==e.currentTarget.dataset.id)
    })
    Toast.success('添加成功')
  },

  // 关闭弹窗
  closeChannel() {
    this.setData({ show: false })
  },

  // 显示更多
  async getMore() {
    this.setData({ show: true })
    if(this.data.channelAllList.length !== 0) return
    const res = await wx.p.request({
      url: 'https://toutiao.itheima.net/v1_0/channels',
      method: 'GET',
      header: {
        Authorization: `Bearer ${store.token}`
      }
    })
    console.log(res);
    this.setData({ channelAllList: res.data.data.channels })
    this.setData({ recommendList: res.data.data.channels.filter(item => !(this.data.TabList.some(element => element.name === item.name))) })
  },

  // 跳转文章详情
  getArticleDetail(e) {
    console.log(e.target.dataset.id);
    wx.navigateTo({
      url: `/pages/detail/detail?id=${e.target.dataset.id}`,
    })
  },

  // 获取列表信息
  async getList(cb) {
    const res = await wx.p.request({
      url: 'https://toutiao.itheima.net/v1_0/articles',
      method: 'GET',
      data: {
        channel_id: this.data.id,
        with_top: 1,
        timestamp: new Date().getTime(),
      }
    })
    this.setData({
      list: res.data.data.results,
    })
    cb && cb()
  },

  // 切换tab
  async changeTab(e) {
    console.log(e.detail);
    console.log(e);
    if (e.detail.index === this.data.id) return
    this.setData({
      id: e.detail.index,
      title: e.detail.title,
    })
    // var list = this.data.loadingList
    // if (list.includes(e.detail.title)) return
    // list.push(e.detail.title)
    // this.setData({ loadingList: list })
    // 获取列表
    this.getList()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['refresh_token', 'token', 'info'],
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    // 重置id
    this.setData({id: 0})
    // 获取tab列表
    const res = await wx.p.request({
      url: 'https://toutiao.itheima.net/v1_0/user/channels',
      method: 'GET',
      header: {
        Authorization: `Bearer ${store.token}`
      },
    })
    console.log(res.data.data);
    this.setData({
      TabList: res.data.data.channels
    })
    // 获取内容列表
    this.getList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh() {
    // 获取内容列表
    this.getList(() => {
      wx.stopPullDownRefresh()  // 数据请求完成后，关闭下拉刷新窗口效果
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  async onReachBottom() {
    const res = await wx.p.request({
      url: 'https://toutiao.itheima.net/v1_0/articles',
      method: 'GET',
      data: {
        channel_id: this.data.id,
        with_top: 1,
        timestamp: new Date().getTime(),
      }
    })
    this.setData({
      list: [...this.data.list, ...res.data.data.results],
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})